package org.gtesoreria

import java.text.SimpleDateFormat;

import org.gtesoreria.utils.MenuOption;

class ConsumoController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        
		if(!params.proveedorId)
			redirect(action: "list", controller:"proveedor")
		else {
			def proveedor = Proveedor.get(params.proveedorId)
			if(params.from && params.to){
				def query = Consumo.createCriteria()
				def consumosEntre = query {
					between("fecha", params.from,params.to)
					eq("proveedor", proveedor)
					order("fecha","asc")				
				}
				
				def total = consumoService.getSubTotal(consumosEntre)
				def totalSubsidio = consumoService.getSubTotalSubsidio(consumosEntre)
				def totalACargoAfiliado = consumoService.getSubTotalACargoAfiliado(consumosEntre)
				def totalDescuento = consumoService.getSubTotalDescuento(consumosEntre)
				def totalProveedor = consumoService.getSubTotalProveedor(consumosEntre)
				params.max = Math.min(params.max ? params.int('max') : 10, 100)
				
				if(proveedor.rubro.codigo == Rubro.rubroFarmacia.codigo){
					//es una farmacia
					render(view:"listFarmacia", 
							model:[consumoInstanceList: consumosEntre, 
								consumoInstanceTotal: consumosEntre.count(), 
								proveedorInstance:proveedor,
								total:total,
								totalSubsidio:totalSubsidio,
								totalACargoAfiliado:totalACargoAfiliado,
								totalDescuento:totalDescuento,
								totalProveedor:totalProveedor,
								proveedorOptions:[new MenuOption(link:"/GTesoreria/proveedor/show/" + params.proveedorId,text:proveedor.nombre),
										new MenuOption(link:"/GTesoreria/consumo/list?proveedorId=" + params.proveedorId,text:"Consumos")],
								breadcrumbOptions:["Proveedores", proveedor.nombre]])
				} else {
				
					[consumoInstanceList: consumosEntre, 
						consumoInstanceTotal: consumosEntre.count(), 
						proveedorInstance:proveedor,
						total:total,
						proveedorOptions:[new MenuOption(link:"/GTesoreria/proveedor/show/" + params.proveedorId,text:proveedor.nombre),
							new MenuOption(link:"/GTesoreria/consumo/list?proveedorId=" + params.proveedorId,text:"Consumos")],
						breadcrumbOptions:["Proveedores", proveedor.nombre]
					]
				}
			} else {
				render(view:"list", model:[proveedorInstance:proveedor, consumoInstanceTotal:0,total:"",
					proveedorOptions:[new MenuOption(link:"/GTesoreria/proveedor/show/" + params.proveedorId,text:proveedor.nombre),
						new MenuOption(link:"/GTesoreria/consumo/list?proveedorId=" + params.proveedorId,text:"Consumos")],
					breadcrumbOptions:["Proveedores", proveedor.nombre]])
			}
			
		}
        
    }

    def create = {
        def consumoInstance = new Consumo()
        consumoInstance.properties = params
        return [consumoInstance: consumoInstance]
    }

    def save = {
        def consumoInstance = new Consumo(params)
        if (consumoInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'consumo.label', default: 'Consumo'), consumoInstance.id])}"
            redirect(action: "show", id: consumoInstance.id)
        }
        else {
            render(view: "create", model: [consumoInstance: consumoInstance])
        }
    }

    def show = {
        def consumoInstance = Consumo.get(params.id)
        if (!consumoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'consumo.label', default: 'Consumo'), params.id])}"
            redirect(action: "list")
        }
        else {
            [consumoInstance: consumoInstance]
        }
    }

	def showPopUp = {
		def consumoInstance = Consumo.get(params.id)
		if (!consumoInstance) {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'consumo.label', default: 'Consumo'), params.id])}"
			redirect(action: "list")
		}
		else {
			[consumoInstance: consumoInstance]
		}
	}
    def edit = {
        def consumoInstance = Consumo.get(params.id)
        if (!consumoInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'consumo.label', default: 'Consumo'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [consumoInstance: consumoInstance]
        }
    }

    def update = {
        def consumoInstance = Consumo.get(params.id)
        if (consumoInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (consumoInstance.version > version) {
                    
                    consumoInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'consumo.label', default: 'Consumo')] as Object[], "Another user has updated this Consumo while you were editing")
                    render(view: "edit", model: [consumoInstance: consumoInstance])
                    return
                }
            }
            consumoInstance.properties = params
            if (!consumoInstance.hasErrors() && consumoInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'consumo.label', default: 'Consumo'), consumoInstance.id])}"
                redirect(action: "show", id: consumoInstance.id)
            }
            else {
                render(view: "edit", model: [consumoInstance: consumoInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'consumo.label', default: 'Consumo'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def consumoInstance = Consumo.get(params.id)
        if (consumoInstance) {
            try {
                consumoInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'consumo.label', default: 'Consumo'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'consumo.label', default: 'Consumo'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'consumo.label', default: 'Consumo'), params.id])}"
            redirect(action: "list")
        }
    }
	
	def consumos = {
    	def afiliado = Afiliado.get(params.afiliadoId);
		def afiliadosOptions = [new MenuOption(link:"/GTesoreria/afiliado/show/" + afiliado.id, text:afiliado.apellidoNombre),
			new MenuOption(link:"/GTesoreria/adelanto/adelantos?afiliadoId=" + afiliado.id, text:"Adelantos"),
			new MenuOption(link:"/GTesoreria/consumo/consumos?afiliadoId=" + afiliado.id, text:"Consumos"),
			new MenuOption(link:"/GTesoreria/prestamo/prestamo?afiliadoId=" + afiliado.id, text:"Prestamos")]
		def breadcrumbOptions = ["Afiliados", afiliado.apellidoNombre, "Consumos"]
		render(view:"listAfiliado",model:[afiliadoInstance:afiliado, consumoInstanceTotal:0,
			afiliadosOptions:afiliadosOptions, breadcrumbOptions:breadcrumbOptions])
	
	}
	
	def descuentos = {
		def afiliado = Afiliado.get(params.afiliadoId);
		def afiliadosOptions = [new MenuOption(link:"/GTesoreria/afiliado/show/" + afiliado.id, text:afiliado.apellidoNombre),
			new MenuOption(link:"/GTesoreria/adelanto/adelantos?afiliadoId=" + afiliado.id, text:"Adelantos"),
			new MenuOption(link:"/GTesoreria/consumo/consumos?afiliadoId=" + afiliado.id, text:"Consumos"),
			new MenuOption(link:"/GTesoreria/consumo/descuentos?afiliadoId=" + params.id, text:"Descuentos")]
		def breadcrumbOptions = ["Afiliados", afiliado.apellidoNombre, "Consumos"]
		render(view:"listDescuentos",model:[afiliadoInstance:afiliado, consumoInstanceTotal:0,
			afiliadosOptions:afiliadosOptions, breadcrumbOptions:breadcrumbOptions])
	
	}
	
	def consumoService;
	
	def dateUtilsService
	
	def listAfiliado = {
		def afiliado = Afiliado.get(params.afiliadoId);
		Date from = null
		Date to = null
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(params.from instanceof String && params.to instanceof String){
			from = formatoDeFecha.parse(params.from)
			to = formatoDeFecha.parse(params.to)
		}else{
			from = params.from
			to = params.to
		}
		
		
		if(params.from > params.to) {
			flash.message="Fechas Invalidas"
			render(view:"listAfiliado",model:[afiliadoInstance:afiliado, consumoInstanceTotal:0])
			return;
		}
		
		def periods = dateUtilsService.getPeriodsBetween(from,to)
		def showPeriods = dateUtilsService.getPeriodsBetweenToShow(from,to)
		int end = periods.size()-1
		int cant = 0;
		def consumoPorPeriodo = [:]
		def subTotales =[:]
		def subTotalesDesc =[:]
		def total = []
		def totalDescuento =[]
		for(i in 1..end) {
			def consumoSuper = consumoService.consumosSuper(afiliado, periods[i-1],periods[i])
			def consumoInd = consumoService.consumosInd(afiliado, periods[i-1],periods[i])
			def consumoVarios = consumoService.consumosVarios(afiliado, periods[i-1],periods[i])
			def consumoFarmacia = consumoService.consumosFarmacia(afiliado, periods[i-1],periods[i])
			def consumoAuto = consumoService.consumosAuto(afiliado, periods[i-1],periods[i])
			cant += consumoSuper.size + consumoInd.size + consumoVarios.size + consumoFarmacia.size + consumoAuto.size
			def consumoPorRubro = new TreeMap<String, ArrayList<Consumo>>()
			consumoPorRubro.put( Rubro.rubroSuper.codigo, consumoSuper)
			consumoPorRubro.put( Rubro.rubroInd.codigo, consumoInd)
			consumoPorRubro.put( Rubro.rubroVarios.codigo, consumoVarios)
			consumoPorRubro.put( Rubro.rubroFarmacia.codigo, consumoFarmacia)
			consumoPorRubro.put( Rubro.rubroAuto.codigo, consumoAuto)
			consumoPorPeriodo.put(periods[i-1],consumoPorRubro)
			
			def subotalSuper = getSubtotal(consumoSuper)
			def subotalSuperDesc = getSubtotalDescuento(consumoSuper)
			def subotalInd = getSubtotal(consumoInd)
			def subotalIndDesc = getSubtotalDescuento(consumoInd)
			def subotalVarios = getSubtotal(consumoVarios)
			def subotalVariosDesc = getSubtotalDescuento(consumoVarios)
			def subotalFarmacia = getSubtotal(consumoFarmacia)
			def subotalFarmaciaDesc = getSubtotalDescuento(consumoFarmacia)
			def subotalAuto = getSubtotal(consumoAuto)
			def subotalAutoDesc = getSubtotalDescuento(consumoAuto)
			def subtotalPeriodo = subotalSuper + subotalInd + subotalVarios + subotalFarmacia + subotalAuto
			def subtotalPeriodoDesc = subotalSuperDesc + subotalIndDesc + subotalVariosDesc + subotalFarmaciaDesc + subotalAutoDesc
			def s = [(Rubro.rubroSuper.codigo) : subotalSuper,(Rubro.rubroInd.codigo):subotalInd,(Rubro.rubroVarios.codigo):subotalVarios,(Rubro.rubroFarmacia.codigo):subotalFarmacia,(Rubro.rubroAuto.codigo):subotalAuto, (periods[i-1]):subtotalPeriodo]
			def sdesc = [(Rubro.rubroSuper.codigo) : subotalSuperDesc,(Rubro.rubroInd.codigo):subotalIndDesc,(Rubro.rubroVarios.codigo):subotalVariosDesc,(Rubro.rubroFarmacia.codigo):subotalFarmaciaDesc,(Rubro.rubroAuto.codigo):subotalAutoDesc, (periods[i-1]):subtotalPeriodoDesc]
			subTotales.put(periods[i-1], s)
			subTotalesDesc.put(periods[i-1], sdesc)
			total.add(subtotalPeriodo)
			totalDescuento.add(subtotalPeriodoDesc);
		}
		total = total.sum()
		totalDescuento = totalDescuento.sum()
		def rubros = [Rubro.rubroSuper.codigo,Rubro.rubroInd.codigo,Rubro.rubroVarios.codigo,Rubro.rubroFarmacia.codigo,Rubro.rubroAuto.codigo]
		def consumoTotal = consumoPorPeriodo
		periods.remove(periods.last())
		
		def afiliadosOptions = [new MenuOption(link:"/GTesoreria/afiliado/show/" + afiliado.id, text:afiliado.apellidoNombre),
				new MenuOption(link:"/GTesoreria/adelanto/adelantos?afiliadoId=" + afiliado.id, text:"Adelantos"),
				new MenuOption(link:"/GTesoreria/consumo/consumos?afiliadoId=" + afiliado.id, text:"Consumos")]
		render(view:"listAfiliado",model:[afiliadoInstance:afiliado, 
											periodos:periods, 
											showPeriods:showPeriods,
											rubros:rubros,
											subTotales:subTotales,
											subTotalesDesc:subTotalesDesc,
											consumoInstanceList: consumoTotal, 
											consumoInstanceTotal:cant,
											total:total,
											totalDescuento:totalDescuento,
											from:formatoDeFecha.format(from),
											to:formatoDeFecha.format(to),
											afiliadosOptions:afiliadosOptions])
	
	}
	
	Double getSubtotal(List<Consumo> consumos){
		Double result = 0.0;
		for(consumo in consumos){
			result += consumo.monto;
		}
		return result;
	}
	
	Double getSubtotalDescuento(List<Consumo> consumos){
		Double result = 0.0;
		for(consumo in consumos){
			result += consumo.montoDescuento();
		}
		return result;
	}
	
	def adelantoService
	def prestamoService
	
	def listConsumosPeriodo = {
		if(!params.periodo) {
			flash.message="Periodo Invalidas"
			render(view:"listConsumosPeriodo", model:[consumoInstanceTotal:10])
			return;
		}
		Date from = params.periodo
		Date to = dateUtilsService.getFirstDayOfTheNextMonth(from);
		def rubro = params.rubro
		def consumosSuper, consumosInd, consumosAuto, consumosFarmacia, consumosVarios, adelantos = null
		def cuotas = null
		def rubros = [Rubro.rubroSuper.codigo,Rubro.rubroInd.codigo,Rubro.rubroVarios.codigo,Rubro.rubroFarmacia.codigo,Rubro.rubroAuto.codigo,]
		if(rubro == "null" || rubro.equals(Rubro.rubroSuper.nombre ))
			consumosSuper = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroSuper, from, to, Adelanto.A_DESCUENTO)
		if(rubro == "null" || rubro.equals(Rubro.rubroInd.nombre))
			consumosInd = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroInd, from, to, Adelanto.A_DESCUENTO)
		if(rubro == "null" || rubro.equals(Rubro.rubroAuto.nombre))
			consumosAuto = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroAuto, from, to, Adelanto.A_DESCUENTO)
		if(rubro == "null" || rubro.equals(Rubro.rubroFarmacia.nombre ))
			consumosFarmacia = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroFarmacia, from, to, Adelanto.A_DESCUENTO)
		if(rubro == "null" || rubro.equals(Rubro.rubroVarios.nombre ))
			consumosVarios = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroVarios, from, to, Adelanto.A_DESCUENTO)
		if(rubro == "null" || rubro.equals("Adelantos")){
			adelantos = adelantoService.adelantosEntreFechasPorEstado(from, to, Adelanto.A_DESCUENTO)
		}
		if(rubro == "null" || rubro.equals("Prestamos")){
			cuotas = prestamoService.cuotasEntreFechasADescuento(from, to)
		}
		def subTotalSuper, subTotalInd, subTotalAuto, subTotalFarmacia, subTotalVarios, subTotalAdelantos, subTotalCuotas = null
		if(rubro == "null" || rubro ==  Rubro.rubroSuper.nombre )
			subTotalSuper = consumoService.getSubTotal(consumosSuper)
		if(rubro == "null" || rubro ==  Rubro.rubroInd.nombre)
			subTotalInd = consumoService.getSubTotal(consumosInd)
		if(rubro == "null" || rubro ==  Rubro.rubroAuto.nombre )
			subTotalAuto = consumoService.getSubTotal(consumosAuto)
		if(rubro == "null" || rubro ==  Rubro.rubroFarmacia.nombre)
			subTotalFarmacia = consumoService.getSubTotal(consumosFarmacia);
		if(rubro == "null" || rubro ==  Rubro.rubroVarios.nombre)
			subTotalVarios = consumoService.getSubTotal(consumosVarios);
		if(rubro == "null" || rubro ==  "Adelantos")
			subTotalAdelantos = adelantoService.getSubTotal(adelantos);
		if(rubro == "null" || rubro ==  "Prestamos")
			subTotalCuotas = prestamoService.getSubTotal(cuotas);
		
		render(view:"listConsumosPeriodo", model:[consumosSuper:consumosSuper, 
											consumosInd:consumosInd, 
											consumosAuto:consumosAuto, 
											consumosFarmacia:consumosFarmacia,
											consumosVarios:consumosVarios,
											subTotalSuper:subTotalSuper,
											subTotalInd:subTotalInd,
											subTotalAuto:subTotalAuto,
											subTotalFarmacia:subTotalFarmacia,
											subTotalVarios:subTotalVarios,
											periodo:from,
											adelantos:adelantos,
											subTotalAdelantos:subTotalAdelantos,
											cuotas:cuotas,
											subTotalCuotas:subTotalCuotas,
											breadcrumbOptions:["Descuentos","Descuentos por Mes"],
											descuentoOptions:[new MenuOption(link:"/GTesoreria/consumo/listConsumosPeriodoView",text:"Descuento Por Mes")],
											displayButtons:true
											])
		
	}
	
	def cerrarPeriodo = {
		
		Date from = null
		if(!params.periodo) {
			flash.message="Periodo Invalido"
					render(view:"listConsumosPeriodo", model:[consumoInstanceTotal:10])
					return;
		}
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(params.periodo instanceof String){
			from = formatoDeFecha.parse(params.periodo)
		}else{
			from = params.periodo
		}
		
		Date to = dateUtilsService.getFirstDayOfTheNextMonth(from);
		def rubro = params.rubro
		def consumosSuper, consumosInd, consumosAuto, consumosFarmacia, consumosVarios, adelantos = null
		def cuotas = null
		consumosSuper = consumoService.consumosRubroEntreFechas(Rubro.rubroSuper, from, to, Adelanto.A_DESCUENTO)
		consumosInd = consumoService.consumosRubroEntreFechas(Rubro.rubroInd, from, to, Adelanto.A_DESCUENTO)
		consumosAuto = consumoService.consumosRubroEntreFechas(Rubro.rubroAuto, from, to, Adelanto.A_DESCUENTO)
		consumosFarmacia = consumoService.consumosRubroEntreFechas(Rubro.rubroFarmacia, from, to, Adelanto.A_DESCUENTO)
		consumosVarios = consumoService.consumosRubroEntreFechas(Rubro.rubroVarios, from, to, Adelanto.A_DESCUENTO)
		consumoService.updateEstado(consumosSuper, Adelanto.CERRADO)
		consumoService.updateEstado(consumosInd, Adelanto.CERRADO)
		consumoService.updateEstado(consumosAuto, Adelanto.CERRADO)
		consumoService.updateEstado(consumosFarmacia, Adelanto.CERRADO)
		consumoService.updateEstado(consumosVarios, Adelanto.CERRADO)
		adelantos = adelantoService.adelantosEntreFechasPorEstadoSinNorm(from, to, Adelanto.A_DESCUENTO)
		adelantoService.updateEstados(adelantos, Adelanto.CERRADO)
		cuotas = prestamoService.cuotasEntreFechasADescuento(from, to)
		prestamoService.updateCuotasAPagadas(cuotas)
		flash.message = "Periodo "+ formatoDeFecha.format(from) +" Cerrado Exitosamente"
		redirect(action:exportarDescuentos,params:[from:params.from,periodo:params.periodo,estado:Adelanto.CERRADO])
		
	}
	def reportService
	def exportarDescuentos = {
		
		Date from = null
		if(!params.periodo) {
			flash.message="Periodo Invalido"
					render(view:"listConsumosPeriodo", model:[consumoInstanceTotal:10])
					return;
		}
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(params.periodo instanceof String){
			from = formatoDeFecha.parse(params.periodo)
		}else{
			from = params.periodo
		}
		
		Date to = dateUtilsService.getFirstDayOfTheNextMonth(from);
		def rubro = params.rubro
		def consumosSuper, consumosInd, consumosAuto, consumosFarmacia, consumosVarios, adelantos = null
		def cuotas = null
		consumosSuper = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroSuper, from, to, params.estado)
		consumosInd = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroInd, from, to, params.estado)
		consumosAuto = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroAuto, from, to, params.estado)
		consumosFarmacia = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroFarmacia, from, to, params.estado)
		consumosVarios = consumoService.consumosRubroEntreFechasGroupByAfiliado(Rubro.rubroVarios, from, to, params.estado)
		adelantos = adelantoService.adelantosEntreFechasPorEstado(from, to, params.estado)
		if(params.estado == Adelanto.A_DESCUENTO)
			cuotas = prestamoService.cuotasEntreFechasADescuento(from, to)
		else
			cuotas = prestamoService.cuotasPagadasEntreFechas(from, to)
		def file = reportService.createReportDescuentos(
								[("Servicios Supermercados " + formatoDeFecha.format(from)):consumosSuper,
								("Serv. Indumentaria y Deporte " + formatoDeFecha.format(from)):consumosInd,
								("Servicios Automotor " + formatoDeFecha.format(from)):consumosAuto,
								("Farmacia " + formatoDeFecha.format(from)):consumosFarmacia,
								("Servicios Varios " + formatoDeFecha.format(from)):consumosVarios,
								("Adelantos " + formatoDeFecha.format(from)):adelantos,
								("Refinanciaciones " + formatoDeFecha.format(from)):cuotas],
								["Nro",
								"Legajo",
								"Nombre y Apellido",
								"Fecha de Nacimiento",
								"Edad",
								"Lugar de Trabajo",
								"Delegado",
								"Categoria"],
							"Descuentos AGOEC " + formatoDeFecha.format(from) )
		
		response.setHeader('Content-disposition', 'attachment;filename=ReporteDescuentos "+ formatoDeFecha.format(from) +".xls')
		response.setHeader('Content-length', "${file.size()}")
		response.contentType = "application/vnd.ms-excel"
		
		OutputStream out = new BufferedOutputStream(response.outputStream)

		try {
			out.write(file.bytes)

		} finally {
			out.close()
			return false
		}

	}
	
	def listConsumosPeriodoView = {
		
		render(view:"listConsumosPeriodo", model:[breadcrumbOptions:["Descuentos","Descuentos por Mes"],
			descuentoOptions:[new MenuOption(link:"/GTesoreria/consumo/listConsumosPeriodoView",text:"Descuento Por Mes")],displayButtons:false])
	}
	
	def listPorPeriodoView = {
		render(view:"listPorPeriodo", model:[breadcrumbOptions:["Consumos","Consumos por periodo"],
			consumoOptions:[new MenuOption(link:"/GTesoreria/proveedor/importacion",text:"Importar Consumos"), new MenuOption(link:"/GTesoreria/consumo/listPorPeriodoView",text:"Consumos por periodo")], consumoInstanceTotal:0])
	}
	
	def listPorPeriodo = {
		Date from = null
		Date to = null
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(params.from instanceof String && params.to instanceof String){
			from = formatoDeFecha.parse(params.from)
			to = formatoDeFecha.parse(params.to)
		}else{
			from = params.from
			to = params.to
		}
		if(params.from > params.to) {
			flash.message="Fechas Invalidas"
			redirect(action:"listPorPeriodoView")
			return;
		}
		def anSort = params.sort ? params.sort : "fecha"
		def anOrder = params.order ? params.order : "desc"
		params.max = Math.min(params.max ? params.int('max') : 30, 100)
		def consumoss = consumoService.consumosBetweenDates(from,to, anSort, anOrder, params.offset, params.max)
		def cant = consumoss == null ? 0 : consumoss.totalCount
		def rubros = [Rubro.rubroSuper.codigo,Rubro.rubroInd.codigo,Rubro.rubroVarios.codigo,Rubro.rubroFarmacia.codigo,Rubro.rubroAuto.codigo]
		
		
		render(view:"listPorPeriodo",model:[from:formatoDeFecha.format(from),
											to:formatoDeFecha.format(to),
											rubros:rubros,
											consumoInstanceList: consumoss, 
											consumoInstanceTotal:cant,
											consumoOptions:[new MenuOption(link:"/GTesoreria/proveedor/importacion",text:"Importar Consumos"), 
												new MenuOption(link:"/GTesoreria/consumo/listPorPeriodoView",text:"Consumos por periodo")]
											])
	
		
	}
	
	def  refinanciarConsumo = {
		def subMapDescuentos = params.findAll { key, value -> key =~ 'descuento_*'}
		def subMapPrestamos = params.findAll { key, value -> key =~ 'prestamo_*'}
		def subMapPendiente = params.findAll { key, value -> key =~ 'pendiente_*'}
		if(subMapDescuentos){
			for(String key:subMapDescuentos.keySet()){
				String idConsumo = key.replace("descuento_", "")
				def consumo = Consumo.get(idConsumo)
				consumo.estado = Adelanto.A_DESCUENTO;
				consumo.save()
			}
		}
		if(subMapPrestamos){
			for(String key:subMapPrestamos.keySet()){
				String idConsumo = key.replace("prestamo_", "")
				def consumo = Consumo.get(idConsumo)
				consumo.estado = Adelanto.A_PRESTAMO;
				consumo.save()
			}
		}
		if(subMapPendiente){
			for(String key:subMapPendiente.keySet()){
				String idConsumo = key.replace("pendiente_", "")
				def consumo = Consumo.get(idConsumo)
				consumo.estado = Adelanto.PENDIENTE;
				consumo.save()
			}
		}
		redirect(action:"listAfiliado", params:params)
		
	}
	
	def  refinanciarSubtotal = {
		def subMapDescuentos = params.findAll { key, value -> key =~ 'descuento_*'}
		def subMapPrestamos = params.findAll { key, value -> key =~ 'prestamo_*'}
		def subMapPendiente = params.findAll { key, value -> key =~ 'pendiente_*'}
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(subMapDescuentos){
			for(String key:subMapDescuentos.keySet()){
				def sub = key.split("_")
				Date from = formatoDeFecha.parse(sub[1])
				String rubroCodigo = sub[2]
				def consumoss = consumoService.consumosPorPeriodoPorRubro(Afiliado.get(params.afiliadoId), from, rubroCodigo)
				consumoss.each { consumo -> consumo.estado = Adelanto.A_DESCUENTO }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		if(subMapPrestamos){
			for(String key:subMapPrestamos.keySet()){
				def sub = key.split("_")
				Date from = formatoDeFecha.parse(sub[1])
				String rubroCodigo = sub[2]
				def consumoss = consumoService.consumosPorPeriodoPorRubro(Afiliado.get(params.afiliadoId), from, rubroCodigo)
				consumoss.each { consumo -> consumo.estado = Adelanto.A_PRESTAMO }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		if(subMapPendiente){
			for(String key:subMapPendiente.keySet()){
				def sub = key.split("_")
				Date from = formatoDeFecha.parse(sub[1])
				String rubroCodigo = sub[2]
				def consumoss = consumoService.consumosPorPeriodoPorRubro(Afiliado.get(params.afiliadoId), from, rubroCodigo)
				consumoss.each { consumo -> consumo.estado = Adelanto.PENDIENTE }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		redirect(action:"listAfiliado", params:params)
		
	}
	
	def refinanciarPeriodo = {
		def subMapDescuentos = params.findAll { key, value -> key =~ 'descuento_*'}
		def subMapPrestamos = params.findAll { key, value -> key =~ 'prestamo_*'}
		def subMapPendiente = params.findAll { key, value -> key =~ 'pendiente_*'}
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(subMapDescuentos){
			for(String key:subMapDescuentos.keySet()){
				def sub = key.split("_")
				Date from = formatoDeFecha.parse(sub[1])
				def consumoss = consumoService.consumosPorPeriodo(Afiliado.get(params.afiliadoId), from)
				consumoss.each { consumo -> consumo.estado = Adelanto.A_DESCUENTO }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		if(subMapPrestamos){
			for(String key:subMapPrestamos.keySet()){
				def sub = key.split("_")
				Date from = formatoDeFecha.parse(sub[1])
				def consumoss = consumoService.consumosPorPeriodo(Afiliado.get(params.afiliadoId), from)
				consumoss.each { consumo -> consumo.estado = Adelanto.A_PRESTAMO }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		if(subMapPendiente){
			for(String key:subMapPendiente.keySet()){
				def sub = key.split("_")
				Date from = formatoDeFecha.parse(sub[1])
				def consumoss = consumoService.consumosPorPeriodo(Afiliado.get(params.afiliadoId), from)
				consumoss.each { consumo -> consumo.estado = Adelanto.PENDIENTE }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		redirect(action:"listAfiliado", params:params)
	}
	
	def refinanciarTotal = {
		def subMapDescuentos = params.findAll { key, value -> key =~ 'descuento_*'}
		def subMapPrestamos = params.findAll { key, value -> key =~ 'prestamo_*'}
		def subMapPendiente = params.findAll { key, value -> key =~ 'pendiente_*'}
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(subMapDescuentos){
			for(String key:subMapDescuentos.keySet()){
				def consumoss = consumoService.consumosBetweenDates(Afiliado.get(params.afiliadoId), formatoDeFecha.parse(params.from), formatoDeFecha.parse(params.to))
				consumoss.each { consumo -> consumo.estado = Adelanto.A_DESCUENTO }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		if(subMapPrestamos){
			for(String key:subMapPrestamos.keySet()){
				def consumoss = consumoService.consumosBetweenDates(Afiliado.get(params.afiliadoId), formatoDeFecha.parse(params.from), formatoDeFecha.parse(params.to))
				consumoss.each { consumo -> consumo.estado = Adelanto.A_PRESTAMO }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		if(subMapPendiente){
			for(String key:subMapPendiente.keySet()){
				def consumoss = consumoService.consumosBetweenDates(Afiliado.get(params.afiliadoId), formatoDeFecha.parse(params.from), formatoDeFecha.parse(params.to))
				consumoss.each { consumo -> consumo.estado = Adelanto.PENDIENTE }
				consumoss.each { consumo -> consumo.save()}
			}
		}
		redirect(action:"listAfiliado", params:params)
	}
	
	def listPendientesView = {
		render(view:"listPendientes", model:[breadcrumbOptions:["Pendientes","Pendientes por periodo"],
			pendientesOptions:[new MenuOption(link:"/GTesoreria/consumo/listPendientesView",text:"Pendientes por periodo")], consumoInstanceTotal:0])
	}
	def listPendientes = {
		Date from = null
		Date to = null
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(params.from instanceof String && params.to instanceof String){
			from = formatoDeFecha.parse(params.from)
			to = formatoDeFecha.parse(params.to)
		}else{
			from = params.from
			to = params.to
		}
		if(params.from > params.to) {
			flash.message="Fechas Invalidas"
			redirect(action:"listPendientesView")
			return;
		}
		def anSort = params.sort ? params.sort : "fecha"
		def anOrder = params.order ? params.order : "desc"
		params.max = Math.min(params.max ? params.int('max') : 30, 100)
		def consumoss = consumoService.consumosBetweenDates(from,to, anSort, anOrder, params.offset, params.max, Adelanto.PENDIENTE)
		def total = getSubtotal(consumoss)
		def totalDesc = getSubtotalDescuento(consumoss)
		def cant = consumoss == null ? 0 : consumoss.totalCount
		def rubros = [Rubro.rubroSuper.codigo,Rubro.rubroInd.codigo,Rubro.rubroVarios.codigo,Rubro.rubroFarmacia.codigo,Rubro.rubroAuto.codigo]
		
		def adelantos = adelantoService.adelantosEntreFechasPorEstado(from, to, Adelanto.PENDIENTE)
		def totalAdelantos = adelantoService.getSubTotal(adelantos)
		
		
		render(view:"listPendientes",model:[from:formatoDeFecha.format(from),
											to:formatoDeFecha.format(to),
											rubros:rubros,
											consumoInstanceList: consumoss,
											consumoInstanceTotal:cant,
											adelantos:adelantos,
											totalAdelantos:totalAdelantos,
											total:total,
											totalDesc:totalDesc,
											breadcrumbOptions:["Pendientes","Pendientes por periodo"],
											pendientesOptions:[new MenuOption(link:"/GTesoreria/consumo/listPendientesView",text:"Pendientes por periodo")]
											])
	}
	
	def refinanciarPendiente = {
		
		Date from = null
		Date to = null
		SimpleDateFormat formatoDeFecha = new SimpleDateFormat("MM/yyyy");
		if(params.from instanceof String && params.to instanceof String){
			from = formatoDeFecha.parse(params.from)
			to = formatoDeFecha.parse(params.to)
		}else{
			from = params.from
			to = params.to
		}
		if(params.from > params.to) {
			flash.message="Fechas Invalidas"
			redirect(action:"listPendientesView")
			return;
		}
		
		def subMapDescuentos = params.findAll { key, value -> key =~ 'descuento_*'}
		def subMapPrestamos = params.findAll { key, value -> key =~ 'prestamo_*'}
		
		if(params.adelanto == "true"){
			if(subMapDescuentos){
				for(String key:subMapDescuentos.keySet()){
					String idAfiliado = key.replace("descuento_", "")
					adelantoService.updateEstadoAdelantosPorPeriodo(from, to, idAfiliado, Adelanto.A_DESCUENTO)
				}
			}
			if(subMapPrestamos){
				for(String key:subMapPrestamos.keySet()){
					String idAfiliado = key.replace("prestamo_", "")
					adelantoService.updateEstadoAdelantosPorPeriodo(from, to, idAfiliado, Adelanto.A_DESCUENTO)
				}
			}
		} else {
			
			if(subMapDescuentos){
				for(String key:subMapDescuentos.keySet()){
					String idConsumo = key.replace("descuento_", "")
					def consumo = Consumo.get(idConsumo)
					consumo.estado = Adelanto.A_DESCUENTO;
					consumo.save()
				}
			}
			if(subMapPrestamos){
				for(String key:subMapPrestamos.keySet()){
					String idConsumo = key.replace("prestamo_", "")
					def consumo = Consumo.get(idConsumo)
					consumo.estado = Adelanto.A_PRESTAMO;
					consumo.save()
				}
			}
		}
		redirect(action:"listPendientes", params:params);
		return
	}
}
